'''
Created on 2022/03/08

@author: shenchh
'''
import os
import chardet

if __name__ == '__main__':
    with open('./check_source.log', mode='w', encoding='utf-8') as fh_w:
        is_end_file_blank_line = False
        for path, dirs, files in os.walk('./'):
            for file in files:
                if file.endswith('.h') or file.endswith('.c') or file.endswith('.hpp') or file.endswith('.cpp'):
                    file_path = os.path.join(path, file)
                    ###################################################
                    if is_end_file_blank_line == False :
                        is_end_file_blank_line = True
                        fh_w.write('>>>>Check for empty lines at the end of the file<<<<\n')

                    with open(file_path, mode='r', encoding='utf-8') as fh_r:
                        lines = fh_r.readlines()
                        last_line = lines[-1]
                        if '\n' not in last_line:
                            fh_w.write(f'{file_path}=>Missing empty lines at the end of the file! \n')
                        else:
                            pass
                    ###################################################
                    
        is_encoding_utf8 = False
        for path, dirs, files in os.walk('./'):
            for file in files:
                if file.endswith('.h') or file.endswith('.c') or file.endswith('.hpp') or file.endswith('.cpp'):
                    file_path = os.path.join(path, file)
                    ###################################################
                    if is_encoding_utf8 == False :
                        is_encoding_utf8 = True
                        fh_w.write('>>>>Check for file encoding <<<<\n')

                    with open(file_path, mode='rb') as fh_r:
                        content = fh_r.read()
                        detect_dic = chardet.detect(content)
                        if detect_dic['encoding'] != "utf-8":
                            fh_w.write(f'{file_path}=>is not UTF-8 =>{detect_dic["encoding"]} \n')
                        else:
                            pass
                    ###################################################